import { useState, useEffect } from 'react'
import { Play, Pause, RefreshCw, Download } from 'lucide-react'
import { useKafkaStore } from '@/stores/kafkaStore'
import { kafkaApi, messageApi, MessageLoadMode } from '@/services/kafka'
import { useWebSocket } from '@/hooks/useWebSocket'
import { useTopicPartitions } from '@/hooks/useTopicPartitions'
import TopicSelector from '@/components/kafka/TopicSelector'
import CompactPartitionSelector from '@/components/kafka/CompactPartitionSelector'
import MessageTable from '@/components/kafka/MessageTable'
import toast from 'react-hot-toast'

export default function DataViewer() {
  const [isStreaming, setIsStreaming] = useState(false)
  const [maxMessages, setMaxMessages] = useState(100)
  const [loadMode, setLoadMode] = useState<MessageLoadMode>('earliest')
  const [enableVirtualization, setEnableVirtualization] = useState(true)
  const [viewMode, setViewMode] = useState<'list' | 'table'>('list')
  
  const {
    topics,
    selectedTopic,
    messages,
    isLoading,
    setTopics,
    setSelectedTopic,
    setMessages,
    setLoading,
    clearMessages,
    setConnectionStatus
  } = useKafkaStore()

  const { connected, subscribeTopic, unsubscribeTopic } = useWebSocket()

  // 分区相关状态 - 使用新的hook
  const {
    partitions,
    partitionDetails,
    loading: partitionsLoading,
    error: partitionsError,
    loadPartitions,
    clearPartitions
  } = useTopicPartitions()
  const [selectedPartition, setSelectedPartition] = useState<number | undefined>(undefined)

  // 检测连接状态并加载Topic列表
  useEffect(() => {
    const initializeData = async () => {
      try {
        // 首先检测连接状态
        const connectionResult = await kafkaApi.testConnection()
        if (connectionResult.success) {
          setConnectionStatus('已连接', true)

          // 连接成功后加载Topic列表
          const topicList = await kafkaApi.getTopics()
          setTopics(topicList)
        } else {
          setConnectionStatus('连接失败', false)
          toast.error('Kafka连接失败，请检查配置')
        }
      } catch (error) {
        console.error('初始化数据失败:', error)
        setConnectionStatus('连接失败', false)
        toast.error('无法连接到Kafka服务器')
      }
    }

    initializeData()
  }, [setTopics, setConnectionStatus])

  // 当选择的Topic变化时，加载分区信息
  useEffect(() => {
    if (selectedTopic) {
      loadPartitions(selectedTopic)
      setSelectedPartition(undefined) // 重置分区选择
    } else {
      clearPartitions()
      setSelectedPartition(undefined)
    }
  }, [selectedTopic, loadPartitions, clearPartitions])

  // 加载历史消息
  const loadMessages = async () => {
    if (!selectedTopic) return

    setLoading(true)
    try {
      const msgs = await messageApi.getMessages(selectedTopic, {
        maxMessages: loadMode === 'all' ? 10000000 : maxMessages, // 全量模式支持1000万条
        loadMode,
        fromBeginning: loadMode === 'earliest' || loadMode === 'all', // 全量和从头开始都要从beginning读取
        partition: selectedPartition // 添加分区筛选
      })
      setMessages(msgs)

      const modeText = {
        all: '全量',
        earliest: '从头开始'
      }[loadMode]

      const partitionText = selectedPartition !== undefined ? ` (分区 ${selectedPartition})` : ''
      toast.success(`${modeText}加载了 ${msgs.length} 条消息${partitionText}`)
    } catch (error) {
      console.error('加载消息失败:', error)
      toast.error('加载消息失败，请检查连接状态')
    } finally {
      setLoading(false)
    }
  }

  // 开始/停止实时流
  const toggleStreaming = () => {
    if (!selectedTopic) {
      toast.error('请先选择一个Topic')
      return
    }

    if (!connected) {
      toast.error('WebSocket未连接')
      return
    }

    if (isStreaming) {
      unsubscribeTopic(selectedTopic)
      setIsStreaming(false)
    } else {
      subscribeTopic(selectedTopic)
      setIsStreaming(true)
    }
  }

  // 导出消息
  const exportMessages = () => {
    if (messages.length === 0) {
      toast.error('没有消息可导出')
      return
    }

    // 根据当前查看模式选择导出格式
    if (viewMode === 'table') {
      // 表格模式：导出CSV格式，仅包含value的结构化数据
      exportAsCSV()
    } else {
      // 列表模式：导出JSON格式，包含完整消息信息
      exportAsJSON()
    }
  }

  // 导出为JSON格式
  const exportAsJSON = () => {
    const dataStr = JSON.stringify(messages, null, 2)
    const dataBlob = new Blob([dataStr], { type: 'application/json' })
    const url = URL.createObjectURL(dataBlob)

    const link = document.createElement('a')
    link.href = url
    link.download = `kafka-messages-${selectedTopic}-${new Date().toISOString().slice(0, 19)}.json`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(url)

    toast.success('消息导出成功 (JSON格式)')
  }

  // 导出为CSV格式
  const exportAsCSV = () => {
    // 收集所有可能的字段
    const allFields = new Set<string>()
    const validMessages = messages.filter(msg =>
      typeof msg.value === 'object' && msg.value !== null
    )

    if (validMessages.length === 0) {
      toast.error('没有可导出的结构化数据')
      return
    }

    validMessages.forEach(message => {
      if (typeof message.value === 'object' && message.value !== null) {
        Object.keys(message.value).forEach(key => allFields.add(key))
      }
    })

    const fields = Array.from(allFields).sort()

    // 生成CSV内容
    const headers = fields.join(',')
    const csvContent = [
      headers,
      ...validMessages.map(message => {
        return fields.map(field => {
          const value = message.value[field]
          let cellValue = ''

          if (value === null || value === undefined) {
            cellValue = ''
          } else if (typeof value === 'object') {
            cellValue = JSON.stringify(value)
          } else {
            cellValue = String(value)
          }

          // 处理包含逗号、引号或换行符的值
          if (cellValue.includes(',') || cellValue.includes('"') || cellValue.includes('\n')) {
            cellValue = `"${cellValue.replace(/"/g, '""')}"`
          }

          return cellValue
        }).join(',')
      })
    ].join('\n')

    // 下载文件
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
    const link = document.createElement('a')
    const url = URL.createObjectURL(blob)
    link.setAttribute('href', url)
    link.setAttribute('download', `kafka-messages-${selectedTopic}-${new Date().toISOString().slice(0, 19)}.csv`)
    link.style.visibility = 'hidden'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(url)

    toast.success('消息导出成功 (CSV格式)')
  }

  return (
    <div className="space-y-8">
      {/* 页面标题 */}
      <div className="text-center lg:text-left">
        <h1 className="text-3xl font-bold gradient-text mb-2">数据查看器</h1>
        <p className="text-lg text-gray-600">实时查看Kafka消息流，支持多种加载模式和数据导出</p>
      </div>

      {/* 控制面板 */}
      <div className="card hover-lift">
        <div className="card-header">
          <h3 className="card-title">控制面板</h3>
          <p className="card-description">选择Topic和配置加载参数</p>
        </div>
        <div className="card-content">
          <div className="space-y-6">
            {/* Topic选择区域 */}
            <div className="flex flex-col lg:flex-row lg:items-start space-y-4 lg:space-y-0 lg:space-x-6">
              {/* Topic选择器 */}
              <div className="flex-1 min-w-0">
                <TopicSelector
                  topics={topics}
                  selectedTopic={selectedTopic}
                  onTopicChange={setSelectedTopic}
                />
              </div>

              {/* 分区选择器 - 紧凑版本 */}
              {selectedTopic && (
                <div className="flex-shrink-0">
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    分区筛选
                  </label>
                  <CompactPartitionSelector
                    partitions={partitions}
                    partitionDetails={partitionDetails}
                    selectedPartition={selectedPartition}
                    onPartitionChange={setSelectedPartition}
                    loading={partitionsLoading}
                    error={partitionsError}
                    topicName={selectedTopic}
                  />
                </div>
              )}

              {/* 加载模式选择 */}
              <div className="flex items-center space-x-3 p-3 bg-blue-50 rounded-lg border border-blue-200">
                <label className="text-sm font-semibold text-blue-700 whitespace-nowrap">
                  加载模式:
                </label>
                <select
                  value={loadMode}
                  onChange={(e) => setLoadMode(e.target.value as MessageLoadMode)}
                  className="input w-36 bg-white border-blue-300 focus:border-blue-500"
                >
                  <option value="earliest">从头开始</option>
                  <option value="all">全量加载</option>
                </select>
                <span className="text-xs text-blue-600 font-medium">
                  💡 实时消息请使用"开始流式"
                </span>
              </div>

              {/* 消息数量设置 */}
              {loadMode !== 'all' && (
                <div className="flex items-center space-x-3 p-3 bg-green-50 rounded-lg border border-green-200">
                  <label className="text-sm font-semibold text-green-700 whitespace-nowrap">
                    最大消息数:
                  </label>
                  <select
                    value={maxMessages}
                    onChange={(e) => setMaxMessages(Number(e.target.value))}
                    className="input w-24 bg-white border-green-300 focus:border-green-500"
                  >
                    <option value={50}>50</option>
                    <option value={100}>100</option>
                    <option value={500}>500</option>
                    <option value={1000}>1000</option>
                    <option value={5000}>5000</option>
                  </select>
                </div>
              )}

              {/* 虚拟化开关 */}
              <div className="flex items-center space-x-3 p-3 bg-purple-50 rounded-lg border border-purple-200">
                <label className="flex items-center cursor-pointer">
                  <input
                    type="checkbox"
                    checked={enableVirtualization}
                    onChange={(e) => setEnableVirtualization(e.target.checked)}
                    className="rounded border-purple-300 text-purple-600 focus:ring-purple-500 w-4 h-4"
                  />
                  <span className="ml-3 text-sm font-semibold text-purple-700">虚拟滚动</span>
                </label>
                <span className="text-xs text-purple-600 font-medium">
                  💡 大量数据时自动启用
                </span>
              </div>
            </div>

            {/* 操作按钮 */}
            <div className="flex flex-wrap items-center gap-3">
              <button
                onClick={loadMessages}
                disabled={!selectedTopic || isLoading || isStreaming}
                className="btn-outline hover-lift"
              >
                <RefreshCw className={`h-4 w-4 mr-2 ${isLoading ? 'animate-spin' : ''}`} />
                加载消息
              </button>

              <button
                onClick={toggleStreaming}
                disabled={!selectedTopic || !connected || isLoading}
                className={`btn hover-lift ${isStreaming ? 'btn-secondary' : 'btn-primary'}`}
              >
                {isStreaming ? (
                  <>
                    <Pause className="h-4 w-4 mr-2" />
                    停止流式
                  </>
                ) : (
                  <>
                    <Play className="h-4 w-4 mr-2" />
                    开始流式
                  </>
                )}
              </button>

              <button
                onClick={exportMessages}
                disabled={messages.length === 0}
                className="btn-outline hover-lift bg-green-50 border-green-300 text-green-700 hover:bg-green-100"
                title={`导出为${viewMode === 'table' ? 'CSV' : 'JSON'}格式`}
              >
                <Download className="h-4 w-4 mr-2" />
                导出{viewMode === 'table' ? 'CSV' : 'JSON'}
              </button>

              <button
                onClick={clearMessages}
                disabled={messages.length === 0}
                className="btn-ghost text-red-600 hover:text-red-700 hover:bg-red-50 hover-lift"
              >
                清空
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* 状态信息 */}
      <div className="flex items-center justify-between text-sm text-gray-600">
        <div className="flex items-center space-x-4">
          <span>Topic: {selectedTopic || '未选择'}</span>
          {selectedPartition !== undefined && (
            <span>分区: {selectedPartition}</span>
          )}
          <span>消息数: {messages.length}</span>
          <span className={`flex items-center ${connected ? 'text-green-600' : 'text-red-600'}`}>
            <div className={`w-2 h-2 rounded-full mr-1 ${connected ? 'bg-green-500' : 'bg-red-500'}`} />
            WebSocket {connected ? '已连接' : '未连接'}
          </span>
          {isStreaming && (
            <span className="flex items-center text-blue-600">
              <div className="w-2 h-2 rounded-full mr-1 bg-blue-500 animate-pulse" />
              实时流式中
            </span>
          )}
        </div>
      </div>

      {/* 消息表格 */}
      <MessageTable
        messages={messages}
        loading={isLoading}
        enableVirtualization={enableVirtualization}
        enableSearch={true}
        maxHeight={600}
        viewMode={viewMode}
        onViewModeChange={setViewMode}
      />
    </div>
  )
}
